package com.cccyy.data;

import com.alibaba.fastjson2.JSON;
import com.cccyy.data.entity.RequestHader;
import com.cccyy.data.entity.ResponseBody;
import com.cccyy.data.entity.XmlMsgEntity;
import com.thoughtworks.xstream.XStream;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class XmlTest2Map1 {
    public static void main(String[] args) throws InvocationTargetException, IllegalAccessException, NoSuchMethodException {
        XmlMsgEntity xmlMsgEntity = new XmlMsgEntity();
        RequestHader requestHader = RequestHader.builder().transCode("PAY0001").seqNo("22222266699999").channel("MTT").transTime("20240312").build();
//        RequestHader requestHader = RequestHader.builder().build();
        ResponseBody responseBody = ResponseBody.builder().respCode("000000").respMsg("success").encoding("UTF-8").merId("822233222")
                .txnAmt("120.00").txnNo("33339985858588888").txnType("CD01").version("1.0.1").build();
        xmlMsgEntity.setRequestHader(requestHader);
        xmlMsgEntity.setResponseBody(responseBody);

        String s = textMessageToXml(xmlMsgEntity);
        System.out.println("转换出的xml报文：" + s);

//        Map<String, Object> stringStringMap = xmlToMap(s);
        Map<String, Object> stringStringMap = xmlToMapRecursion(s);

        String json = JSON.toJSONString(stringStringMap);
        System.out.println("转换出的Map数据，以json形式打印为：" + json);

        XmlMsgEntity xmlMsgEntity1 = new XmlMsgEntity();
        //对嵌套的数据需要做递归处理
//        BeanUtils.copyProperties(stringStringMap, xmlMsgEntity1);
//        BeanUtils.populate(xmlMsgEntity1, stringStringMap);

        Map<String, Object> testMap = new HashMap<>();
        //对嵌套的数据需要做递归处理
//        BeanUtils.copyProperties(xmlMsgEntity, testMap);
//        Map<String, String> describe = BeanUtils.describe(xmlMsgEntity1);


        System.out.println("结束了");
    }


    /*这个方法只能转换一层数据，嵌套的数据不能读取到*/
    public static Map<String, Object> xmlToMap(String xmlStr) {
        Map<String, Object> map = new HashMap<String, Object>();
        SAXReader reader = new SAXReader();
        try {
            byte[] bytes = xmlStr.getBytes(StandardCharsets.UTF_8);
            ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);

            Document doc = reader.read(byteArrayInputStream);
            Element root = doc.getRootElement();

            @SuppressWarnings("unchecked")
            List<Element> list = root.elements();
            for (Element e : list) {
                List<Element> elements = e.elements();
                if (null != elements && elements.size() > 0) {
                    Map<String, Object> mapTmp = new HashMap<String, Object>();
                    for (Element element : elements) {
                        mapTmp.put(element.getName(), element.getText());
                    }
                    map.put(e.getName(), mapTmp);
                } else {
                    map.put(e.getName(), e.getText());
                }
            }
            byteArrayInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return map;
    }


    public static Map<String, Object> xmlToMapRecursion(String xmlStr) {
        SAXReader reader = new SAXReader();
        byte[] bytes = xmlStr.getBytes(StandardCharsets.UTF_8);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        try {
            Document doc = reader.read(byteArrayInputStream);
            Element root = doc.getRootElement();
            Map<String, Object> recursion = recursion(root);
            byteArrayInputStream.close();
            return recursion;
        } catch (IOException | DocumentException e) {
            throw new RuntimeException(e);
        }
    }


    public static Map<String, Object> recursion(Element element) {
        List<Element> children = element.elements();
        Map<String, Object> mapTmp = new HashMap<String, Object>();
        for (Element child : children) {
            if (child.elements().isEmpty()) {
                mapTmp.put(child.getName(), child.getText());
            } else {
                mapTmp.put(child.getName(), recursion(child));

            }
        }
        // 处理当前元素本身是否有文本值，注意与子元素的处理逻辑区分
        String elementText = element.getTextTrim();
        if (!elementText.isEmpty() && children.isEmpty()) {
            // 当前元素只有文本内容，没有子元素
            mapTmp.put(element.getName(), elementText);
        }
        return mapTmp;
    }

    /**
     * 将对象转化为xml
     *
     * @param testMessage
     * @return
     */
    public static String textMessageToXml(XmlMsgEntity testMessage) {
        XStream xstream = new XStream();
        xstream.alias("xml", testMessage.getClass());
        return xstream.toXML(testMessage);
    }
}
